package com.wlp.pengpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlp.pengpicturebackend.annotation.AuthCheck;
import com.wlp.pengpicturebackend.common.BaseResponse;
import com.wlp.pengpicturebackend.common.DeleteRequest;
import com.wlp.pengpicturebackend.common.ResultUtils;
import com.wlp.pengpicturebackend.exception.BusinessException;
import com.wlp.pengpicturebackend.exception.ErrorCode;
import com.wlp.pengpicturebackend.exception.ThrowUtils;
import com.wlp.pengpicturebackend.model.dto.user.*;
import com.wlp.pengpicturebackend.model.entity.User;
import com.wlp.pengpicturebackend.model.vo.LoginUserVO;
import com.wlp.pengpicturebackend.model.vo.UserVO;
import com.wlp.pengpicturebackend.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static com.wlp.pengpicturebackend.constant.UserConstant.ADMIN_ROLE;

/**
 * 用户操作
 *
 * @author wlp
 * @date 2025/01/01 11:18
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @Author: wlp
     * @Date: 2025/1/1 11:19
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<java.lang.String>
     **/
//    @AuthCheck(mustRule = ADMIN_ROLE)
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        long userId = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest:
     * @Author: wlp
     * @Date: 2025/1/3 16:29
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<java.lang.Long>
     **/
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取当前登录用户
     *
     * @param request:
     * @Author: wlp
     * @Date: 2025/1/3 16:43
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<com.wlp.pengpicturebackend.model.vo.LoginUserVO>
     **/
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    /**
     * 用户注销
     * @param request:
     * @Author: wlp
     * @Date: 2025/1/6 9:16
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<java.lang.Boolean>
     **/
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.getLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 创建用户
     *
     * @param userAddRequest:
     * @Author: wlp
     * @Date: 2025/1/6 9:55
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<java.lang.Long>
     **/
    @PostMapping("/add")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);
        //默认密码
        final String DEFAULT_PASSWORD = "12345678";
        String encrytPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encrytPassword);
        //插入数据库
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据id获取用户（仅限管理员使用）
     *
     * @param id:
     * @Author: wlp
     * @Date: 2025/1/6 10:02
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<com.wlp.pengpicturebackend.model.entity.User>
     **/
    @GetMapping("/get")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据id，获取包装类
     *
     * @param id:
     * @Author: wlp
     * @Date: 2025/1/6 10:04
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<com.wlp.pengpicturebackend.model.vo.UserVO>
     **/
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVoById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 更新用户
     * @Author: wlp
     * @Date: 2025/1/6 10:10
     * @param userUpdateRequest:
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<java.lang.Boolean>
     **/
    @PostMapping("/update")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtil.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表信息（仅管理员）
     * @Author: wlp
     * @Date: 2025/1/6 10:20
     * @param userQueryRequest:
     * @return: com.wlp.pengpicturebackend.common.BaseResponse<com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.wlp.pengpicturebackend.model.vo.UserVO>>
     **/
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVoByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current= userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current,pageSize,userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    @PostMapping("/delete")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest){
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
}
